const app = getApp();
Page({
  data: {

    date: '', //时间
    dateSwitch: false, //开关
    isProportion: false,
    isThreshold: false,
    proportion: "", //低余额水卡比例提示
    threshold: "",
    areaCodeText: '', //区域码+名称
    onlineThrashTemplateTitle: '', //价格模板名称
    customRechargeTemplateTitle: '', //用户自助充值模板名称 
  },

  onLoad: function (options) {
    this.v_id = options.v_id;
    this.getVillage();
  },

  onReady: function () {
    this.dateTime = this.selectComponent("#dateTime");
  },


  changeSwitch(e) {
    const value = e.detail.value;
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: value
    })
  },

  handleProportionInput(e) {
    let value = e.detail.value;
    if (value > 100) {
      app.showToast("超出百分比最大值");
      value = 100;
    }
    this.setData({
      proportion: value
    });
  },

  handleThresholdInput(e) {
    this.setData({
      threshold: e.detail.value
    })
  },


  getVillage() {
    app.ajax({
      url: "Partner/Village/getVillage",
      data: {
        id: this.v_id
      },
      success: res => {
        if (res.data.code == 1000) {
          console.log(res.data.data);
          const data = res.data.data;


          //设置开启switch的时间
          let d = new Date();
          let date = `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}`
          this.setData({
            dateSwitch: data.check_record_card == 1 ? true : false,
            date: data.check_record_card == 1 ? data.check_record_card_time : date,
            isProportion: data.prompt_on == 1 ? true : false,
            proportion: data.prompt_on == 1 ? data.prompt_value : '',
            isThreshold: data.threshold_on == 1 ? true : false,
            threshold: data.threshold_value > 0 ? Number.parseFloat(data.threshold_value) : '',
            areaCodeText: data.area_code_id > 0 ? `${data.area_code_name}(${data.area_code})` : '',
            onlineThrashTemplateTitle: data.sell_water_title || '平台默认模板',
            customRechargeTemplateTitle: data.template_title || '平台默认模板'
          })
          this.area_code_id = data.area_code_id > 0 ? data.area_code_id : '';
          this.sell_id = data.sell_id || 0;
          this.template_id = data.template_id || 0;
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        app.showToast("请求失败");
      }
    })
  },
  //提交数据
  confirmBtn() {
    wx.showLoading({
      mask: true
    });
    app.ajax({
      url: 'Partner/Village/bindTemplate',
      data: {
        check_card_record: this.data.dateSwitch == true ? 1 : 2,
        check_record_card_time: this.data.dateSwitch == true ? this.data.date : "",
        village_id: this.v_id,
        template_id: this.template_id,
        set_template_id: this.sell_id,
        area_code_id: this.area_code_id,
        prompt_on: this.data.isProportion ? 1 : 2,
        prompt_value: this.data.isProportion ? this.data.proportion : '',
        threshold_on: this.data.isThreshold ? 1 : 2,
        threshold_value: this.data.threshold,
      },
      success: res => {
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "success");
          setTimeout(() => {
            let pages = getCurrentPages();
            let targetPage = pages[pages.length - 2];
            targetPage.reloadData();
            wx.navigateBack()
          }, 2000)
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        wx.hideLoading()
      }
    })
  },

  //跳转到设置区域码中间页面
  navMiddleAreaCode() {
    let _self = this;
    wx.navigateTo({
      events: {
        acceptDataFromMiddleAreaCode: function (data) {
          if (data) {
            _self.setModal(data);
          }
        }
      },
      url: '../middle/areaCode/index?type=2',
      success: function (res) {
        res.eventChannel.emit("acceptDataFromOpenerPage", {
          area_code_id: _self.area_code_id
        })
      },
    })
  },

  setTemplate(results) {
    if (this.currentType == 1) {
      this.setData({
        onlineThrashTemplateTitle: results.data.template_title,
      })
      this.sell_id = results.template_id;
    } else {
      this.setData({
        customRechargeTemplateTitle: results.data.template_title,
      })
      this.template_id = results.template_id;
    }
  },

  navMiddleTemplate(e) {
    let _self = this;
    const type = e.currentTarget.dataset.type;
    this.currentType = type;
    wx.navigateTo({
      events: {
        acceptDataFromMiddleTemplate: function (data) {
          if (data) {
            if (type == 1) {
              _self.setData({
                onlineThrashTemplateTitle: data.template_title,
              })
              _self.sell_id = data.id;
            } else {
              _self.setData({
                customRechargeTemplateTitle: data.template_title
              })
              _self.template_id = data.id;
            }
          }
        },
      },
      url: '../middle/template/index?type=' + type,
      success: function (res) {
        res.eventChannel.emit("acceptDataFromOpenerPage", {
          template_id: type == 1 ? _self.sell_id : _self.template_id
        })
      },
    })
  },



  setModal(data) {
    console.log("收到的数据", data);
    this.area_code_id = data.id; //区域码id
    this.setData({
      areaCodeText: `${data.name}(${data.area_code})`
    })
  },

  //获取模板
  getMode(template_species) {
    return new Promise((resolve, reject) => {
      app.ajax({
        url: "Partner/Village/templateList",
        data: {
          row: 9999,
          template_species, //2打水 1充值
        },
        success: res => {
          if (res.statusCode == 200) {
            if (res.data.code == 1000) {
              const data = res.data.data.data;
              data.unshift({
                id: "",
                template_title: "通用模板"
              })
              resolve(data);
            } else {
              reject(res.data.message)
            }
          } else {
            reject("服务器错误")
          }
        },
        error: e => {
          reject("请求失败")
        }
      })
    });
  },


  //获取区域码
  getRegionCode() {
    return new Promise((resolve, reject) => {
      app.ajax({
        url: "Partner/Village/getAreaCode",
        success: res => {
          if (res.statusCode == 200) {
            if (res.data.code == 1000) {
              resolve(res.data.data);
            } else {
              reject(res.data.message)
            }
          } else {
            reject("服务器错误")
          }
        },
        error: e => {
          reject("请求失败")
        }
      })
    })
  },

  navAddRecharge() {
    wx.redirectTo({
      url: '../template/index?type=1',
    })
  },

  navAddThrash() {
    wx.redirectTo({
      url: '../template/index?type=2',
    })
  },

  //跳转到区域码添加
  navAddRegionCode() {
    wx.navigateTo({
      url: '../regionCode/add/add'
    })
  },

  //打开日期组件
  showDateTime() {
    this.dateTime.show();
  },


  //修改日期组件数据
  changeDate(e) {
    this.setData({
      date: e.detail.result
    })
  },


  // picker选择
  change(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },

  //switch选择
  limitTime(e) {
    this.setData({
      dateSwitch: !this.data.dateSwitch
    })
  }

})